package br.com.sovi.mobile.j2me;

import br.com.sovi.mobile.j2me.gps.UpdateHandler;
import br.com.sovi.mobile.j2me.gps.UpdateListener;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;

/**
 *
 * @author Realm
 */
public class LocationManager {

    private static LocationProvider provider;

    private static UpdateHandler handler;

    public static LocationProvider getProvider(Criteria criteria) throws LocationException, InterruptedException {
        if (provider == null) {
            provider = LocationProvider.getInstance(criteria);
        }

        return provider;
    }

    public static void startGPS(UpdateListener listener, int interval, Criteria criteria) {
        handler = new UpdateHandler(listener);

        GPSListener gpsListener = new GPSListener() {

            public void log(String text) {
                Log.getLog().log(text);
            }

            public void locationUpdated(LocationProvider provider, Location location) {
                log("Location Updated.");
                handler.handleUpdate(location);
            }

            public void providerStateChanged(LocationProvider provider, int arg1) {
                log("Provider State Changed: " + arg1);
            }
        };

        try {
            getProvider(criteria);

            do {
                int p = 0;

                if (provider != null) {
                    Log.getLog().log("Provider capturado.");
                    new Thread(handler).start();

                    int timeout = -1;
                    int maxage = -1;
                    provider.setLocationListener(gpsListener, interval, timeout, maxage);
                } else {
                    Log.getLog().log("Provider t" + p++);
                    Thread.sleep(2000);
                }
            } while (provider == null);

        } catch (Exception ex) {
            ex.printStackTrace();
            Log.getLog().log("Exception.: " + ex.getClass().getName() + " > " + ex.getMessage());
        }
    }

    public static void stopGps() {
        if (handler != null) {
            handler.stop();
        }
    }

}
